package com.example.demo.web.config;

import com.example.demo.core.exception.StatusCode;
import com.example.demo.core.handler.exception.ExceptionInfoBO;
import com.example.demo.core.handler.exception.ResultBO;
import com.example.demo.core.handler.exception.ResultTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class ExceptionConfig {
    private final Logger logger = LoggerFactory.getLogger(WebConfig.class);
    /**
     * 参数校验异常
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResultBO<?> argumentExceptionHandler(MethodArgumentNotValidException exception) {
        String message = exception.getBindingResult().getFieldError().getDefaultMessage();
        logger.info("发生参数异常:{}", message);
        return ResultTool.error(new ExceptionInfoBO(StatusCode.MethodArgumentNotValidException.getCode(), message));
    }
}
